package net.xinshi.service.business.impl;

import com.alibaba.fastjson.JSON;
import net.xinshi.dal.automapper.model.ApiLog;
import net.xinshi.exception.ApiException;
import net.xinshi.model.*;
import net.xinshi.service.atom.IAtomApiLogService;
import net.xinshi.service.business.IApiLogService;
import net.xinshi.utils.BeanUtils;
import net.xinshi.utils.ErrorCode;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author <a href="mailto:liukuo@xinshi.net">liukuo</a>
 * @version 1.0
 * @description
 * @since 2017/6/27.
 */
@Service("ApiLogService")
public class ApiLogServiceImpl implements IApiLogService {
    private static final Logger LOGGER = LogManager.getLogger(ApiLogServiceImpl.class);
    @Autowired
    private IAtomApiLogService atomApiLogService;

    @Override
    public Long addLog(ApiLogInputDTO input) {
        LOGGER.info("增加Api日志，入参对象为 {}", JSON.toJSONString(input));
        try {
            if (input == null) {
                throw new ApiException(ErrorCode.ERR_REST_INPUT_VALIDATION_REJECTED, "增加api调用日志功能入参对象为空");
            }
            ApiLog apiLog = BeanUtils.beanCopy(input, ApiLog.class);
            atomApiLogService.save(apiLog);
            return apiLog.getId();
        } catch (Exception e) {
            LOGGER.error("增加Api日志，保存失败，{}", e);
            if (e instanceof ApiException) {
                throw (ApiException) e;
            }
            e.printStackTrace();

            throw new ApiException(ErrorCode.ERR_DATA_OPER_ERROR);
        }
    }

    @Override
    public BasePageOutputDTO<ApiLogOutputDTO> queryApiLogList(ApiLogPageInputDTO input) {
        LOGGER.info("查询API日志，分页查询入参对象为 {}", input);
        try {
            if (input == null) {
                throw new ApiException(ErrorCode.ERR_REST_INPUT_VALIDATION_REJECTED, "查询API日志，分页查询入参对象为空");
            }
            Map<String, Object> map = new HashMap<>();
            map.put("apiId", input.getApiId());
            map.put("apiName", input.getApiName());
            map.put("apiUrl", input.getApiUrl());
            map.put("serialNo", input.getSerialNo());
            map.put("responseCode", input.getResponseCode());
            if (StringUtils.isNotBlank(input.getBeginCallTime())) {
                map.put("beginCallTime", input.getBeginCallTime());
            }
            if (StringUtils.isNotBlank(input.getEndCallTime())) {
                map.put("endCallTime", input.getEndCallTime());
            }
            //{start},${pageSize}
            map.put("start", input.getStart());
            map.put("pageSize", input.getPageSize());

            long beginTime = System.currentTimeMillis();
            List<ApiLog> dataList = atomApiLogService.searchApiLogByCriteria(map);
            Integer count = atomApiLogService.searchApiLogCount(map);
            long endTime = System.currentTimeMillis();

            LOGGER.info("查询API日志，查询耗时:{}", (endTime - beginTime));
            BasePageOutputDTO<ApiLogOutputDTO> outputs = new BasePageOutputDTO<ApiLogOutputDTO>();
            outputs.setPageSize(input.getPageSize());
            outputs.setCurrentPage(input.getStart());
            if (dataList != null) {
                for (ApiLog r : dataList) {
                    ApiLogOutputDTO output = BeanUtils.beanCopy(r, ApiLogOutputDTO.class);
                    outputs.addList(output);
                }
                outputs.setTotalSize(count);
            }
            return outputs;
        } catch (Exception e) {
            LOGGER.error("查询API日志，分页查询失败，{}", e);
            if (e instanceof ApiException) {
                throw (ApiException) e;
            }
            throw new ApiException(ErrorCode.ERR_DATA_OPER_ERROR);
        }
    }

    @Override
    public ApiLogOutputDTO getLog(BaseIdInputDTO input) {
        LOGGER.info("查询API日志，查询入参对象为 {}", input);
        try {
            if (input == null) {
                throw new ApiException(ErrorCode.ERR_REST_INPUT_VALIDATION_REJECTED, "查询API日志，查询入参对象为空");
            }
            ApiLog apiLog = atomApiLogService.selectByKey(input.getId());
            if (apiLog != null) {
                return BeanUtils.beanCopy(apiLog, ApiLogOutputDTO.class);
            }
            return null;
        } catch (Exception e) {
            LOGGER.error("查询API日志，分页查询失败，{}", e);
            if (e instanceof ApiException) {
                throw (ApiException) e;
            }
            throw new ApiException(ErrorCode.ERR_DATA_OPER_ERROR);
        }
    }
}
